﻿using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using SoftSource.Common;
using SoftSource.MVVMC;

namespace SoftSource.Controls
{
    public partial class AutoGridEditorView : UserControl, IView<IAutoGridEditorViewModelConsume>
    {
        public AutoGridEditorView()
        {
            InitializeComponent();

            this.AutoDataGrid.AutoGeneratingColumn += new EventHandler<DataGridAutoGeneratingColumnEventArgs>(AutoDataGrid_AutoGeneratingColumn);
            this.AutoDataGrid.RowEditEnded += new EventHandler<DataGridRowEditEndedEventArgs>(AutoDataGrid_RowEditEnded);
        }

        void AutoDataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
        {
            this.ViewModel.OnAutoGenerating.TryInvoke(e);
        }

        void AutoDataGrid_RowEditEnded(object sender, DataGridRowEditEndedEventArgs e)
        {
            this.ViewModel.Save.TryInvoke(e.Row.DataContext).Subscribe();
        }

        #region IView<IAutoGridEditorViewModelConsume> Members

        public IAutoGridEditorViewModelConsume ViewModel
        {
            get { return this.DataContext as IAutoGridEditorViewModelConsume; }
            set { this.DataContext = value; }
        }

        private void Add_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            var obj = this.ViewModel.Add.TryInvoke();

            this.AutoDataGrid.ScrollIntoView(obj, this.AutoDataGrid.CurrentColumn);
            this.AutoDataGrid.SelectedItem = obj;
            this.AutoDataGrid.BeginEdit();
        }

        private void Delete_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            MessageBoxResult result = MessageBox.Show(
                "Are you sure you want to delete?", 
                "Warning", 
                MessageBoxButton.OKCancel);

            if (result == MessageBoxResult.OK)
            {
                this.ViewModel.Delete.TryInvoke(
                    this.AutoDataGrid.SelectedItem,
                    () => this.AutoDataGrid.SelectedIndex = -1);
            }
        }

        #endregion
    }
}
